package com.app.mvvmkotlindemo.network

import android.text.TextUtils
import com.app.mvvmkotlindemo.BuildConfig
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.everyline.baselibrary.network.BaseNetworkApi

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by on 2020/11/23.
 * 天天挂线
 *  746608431@qq.com
 *  描述:TODO
 */

class RetrofitClient : BaseNetworkApi() {

    companion object {
        val instance: RetrofitClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitClient() }
    }

    inner class CustomIntercept : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val builder = request.newBuilder()
            // 解决下载文件时，response.body().contentLength()返回-1
            builder.header("Accept-Encoding", "identity")

//            val savedToken: String = LoginStateUtils.getToken()
//
//            if (!TextUtils.isEmpty(savedToken)) {
//                builder.header("jwtToken", savedToken)
//            }

            builder.header("appVersion", AppUtils.getAppVersionName())
            builder.header("phoneBrand", DeviceUtils.getManufacturer())
            builder.header("phoneModel", DeviceUtils.getModel())
            builder.header("phoneVersion", DeviceUtils.getSDKVersionName())

            val requestBuilder = builder.method(request.method, request.body)
            return chain.proceed(requestBuilder.build())
        }
    }

    override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {

        if (BuildConfig.DEBUG) {
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            builder.addInterceptor(loggingInterceptor)
        }
        builder.apply {
            addInterceptor(CustomIntercept())
            connectTimeout(30, TimeUnit.SECONDS)
            readTimeout(30, TimeUnit.SECONDS)
            writeTimeout(30, TimeUnit.SECONDS)
        }
        return builder
    }

    override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
        return builder.apply {
            addConverterFactory(GsonConverterFactory.create())
            addConverterFactory(ScalarsConverterFactory.create())
        }
    }
}